package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.core.handlers.common.CommonBookHandler
import top.kikt.book.core.handlers.common.ContentPagingHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.getUrl
import java.nio.charset.Charset

class Lidapoly : BaseBookHandler(), CommonBookHandler, ContentPagingHandler {
    override val host: String
        get() = "www.lidapoly.com"

    override fun forceCharset(): Charset {
        return Charset.forName("utf8")
    }

    override fun parseContent(document: Document): String {
        return document.select("#content").bookText()
    }

    override fun nextContentPageUrl(document: Document, url: String): String? {
//        <div class="section-opt m-bottom-opt" style="margin: 0px; top: 0">
//
//        <a href="javascript:void(0);" onclick="swal({title: '已经浏览到第一章了！',type: 'info'});" style="outline: none; text-decoration: none">上一章</a>
//
//        <span class="xs-hidden">← </span>
//        <a href="/ldks/19658/">章节列表</a>
//        <span class="xs-hidden">→</span>
//
//        <a href="/ldks/19658/4090651_2.html">下一页</a>
//
//        <a href="/19658.html">TXT下载</a>
//        <a href="javascript:;" class="xs-hidden" onclick="javascript:addBookMark();">加入书签</a>
//
//        </div>

        val next = document.select(".section-opt > a")

        var a: Element? = null
        for (element in next) {
            if (element.text() == "下一页") {
                a = element
                break
            }
        }
        return a?.getUrl(url)
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        return handleChapter(chapterMetaEntity)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val menus = document.select(".section-box")[1].select("li > a")

        return menus.mapIndexed { index, it ->
            val href = it.getUrl(menuUrl)
            val name = it.text()
            ChapterMetaEntity(name, index, href, it)
        }
    }

}